#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：__init__.py
@Author ：zqy
@Email : zqingy@work@163.com
@note: 模型映射
"""
from typing import Optional, Union, Any, Dict, List

from sqlalchemy import JSON
from sqlalchemy.orm.attributes import flag_modified

from application.util.MysqlUtil import mysql_db, mysql_session


class BaseMapper:
    """
    Mapper基类 - 实现基本增删查改
    """
    model: mysql_db.Model = None

    @classmethod
    def count(cls, filter: list = None) -> int:
        """
        数据总条数
        :param filter: 过滤条件列表
        :return: 数据总条数
        """
        _filter = filter or []
        return cls.model.query.filter(*_filter).count()

    @classmethod
    def get_info_list(cls, page_size: int = 10, current_page: int = 1, filter: list = None,
                      order_by: list = None) -> List[mysql_db.Model]:
        """
        获取数据列表
        :param page_size: 每页条数
        :param current_page: 当前页
        :param filter: 筛选条件
        :param order_by: 排序条件
        :return: 数据列表
        """
        _filter = filter or []
        _order_by = order_by or []
        offset: int = (current_page - 1) * page_size
        return cls.model.query.filter(*_filter).order_by(*_order_by).limit(limit=page_size).offset(offset=offset).all()

    @classmethod
    def get_info_by_id(cls, model_id: int) -> Optional[mysql_db.Model]:
        """
        根据数据ID获取数据信息
        :param model_id: 数据ID
        :return: 数据信息 | None
        """
        return cls.model.query.filter_by(id=model_id).first()

    @classmethod
    def insert(cls, model: mysql_db.Model) -> bool:
        """
        插入一条数据
        :param model: 数据模型
        :return:
        """
        try:
            mysql_session.add(instance=model)
            mysql_session.commit()
            return True
        except Exception as e:
            mysql_session.rollback()
            raise e
            return False

    @classmethod
    def update_by_id(cls, model_id: int, update_dict: dict) -> bool:
        """
        根据ID更新数据
        :param model_id: 数据ID
        :param update_dict: 更新的数据
        :return:
        """
        try:
            m = cls.model.get_by_id(model_id)
            m.update_orm_object(data=update_dict)
            mysql_session.add(m)
            mysql_session.commit()
            return True
        except Exception as e:
            print(e)
            mysql_session.rollback()
            return False

    @classmethod
    def delete_by_ids(cls, id_list: Union[list, int], autocommit=True) -> bool:
        """
        根据id删除数据信息
        :param id_list: 数据id列表
        :return: 是否删除成功
        """
        if isinstance(id_list, int):
            id_list = [id_list]
        cls.model.query.filter(cls.model.id.in_(id_list)).delete()
        if autocommit:
            try:
                mysql_session.commit()
                return True
            except Exception:
                mysql_session.rollback()
                return False
        return True

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.model.columns}
